/**
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-01-14 17:39:31
 * @Description  : 考试记录接口控制器
 */
const Mysequelize = require('@/models')
const R = require('@/models/Response')
const {
  ExamHistory,
  Paper,
  Question,
  ErrorQuestion
} = require('@/models/model')
const { ERROR_USER_CODE } = require('@/constants/errorCode')
const { generatId } = require('@/utils/idUtil')
const { delModel, sortModel } = require('@/utils/controllerCommon')
const { Op } = require('sequelize')

/**
 * 列表查询考试记录接口
 * @param {*} ctx
 * @returns
 */
module.exports.listExamHistory = async (ctx) => {
  const { userId, paperId, type } = ctx.query
  // 默认查询普通作答记录
  const whereCondition = {
    type: 1
  }
  if (userId !== undefined) {
    whereCondition.userId = userId
  }
  if (paperId !== undefined) {
    whereCondition.paperId = BigInt(paperId)
  }
  if (type !== undefined) {
    whereCondition.type = +type
  }
  const orderCondition = [['createTime', 'desc']]

  const { page, pageSize } = ctx.query
  const start = (page - 1) * pageSize
  const { rows, count } = await ExamHistory.findAndCountAll({
    where: whereCondition,
    // include: [
    //   {
    //     model: Paper,
    //     include: [
    //       {
    //         model: Question
    //       }
    //     ]
    //   }
    // ],
    offset: +start,
    limit: +pageSize,
    order: orderCondition,
    distinct: true
  })

  ctx.body = R.success({
    page,
    pageSize,
    total: count,
    pages: Math.ceil(count / pageSize),
    items: rows
  })
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 创建考试记录接口
 * @param {*} ctx
 */
module.exports.createExamHistory = async (ctx) => {
  const { paperId, answers, type } = ctx.request.body
  const t = await Mysequelize.transaction()
  const nextId = generatId()
  const sort = await ExamHistory.max('sort')

  let finaType = type ? +type : 1
  let createObj = {
    id: nextId,
    paperId,
    userId: ctx.user.id,
    answers,
    type: +finaType,
    sort: sort + 1,
    createUser: ctx.user.id,
    updateUser: ctx.user.id
  }
  try {
    // 到这里可以进行考试记录的添加了,排序字段默认是最大值
    // 需要移除之前的考试记录

    if (finaType === 1) {
      await ExamHistory.destroy({
        where: {
          type: {
            [Op.in]: [1, 2]
          },
          paperId,
          userId: ctx.user.id
        },
        transaction: t
      })
      const examHistory = await ExamHistory.create(createObj, {
        transaction: t
      })
      // 根据answer和正确答案比对，实现错题
      const questions = await Question.findAll({
        where: {
          paperId
        }
      })

      const paperInfo = await Paper.findByPk(BigInt(paperId))

      const yourAnswerArr = answers.split(',')
      let incre = 1
      const errorSort = await ErrorQuestion.max('sort')

      // 在此之前，需要删除用户之前的错题
      await ErrorQuestion.destroy({
        where: {
          paperId,
          userId: ctx.user.id
        },
        transaction: t
      })

      for (let i = 0; i < questions.length; i++) {
        if (questions[i].answer !== yourAnswerArr[i]) {
          // 加入错题
          await ErrorQuestion.create(
            {
              id: generatId(),
              paperId,
              userId: ctx.user.id,
              examId: paperInfo.examId,
              questionId: questions[i].id,
              createUser: ctx.user.id,
              updateUser: ctx.user.id,
              sort: errorSort + incre
            },
            {
              transaction: t
            }
          )
          incre++
        }
      }
    } else if (finaType === 2) {
      // 错题作答
      await ExamHistory.destroy({
        where: {
          type: {
            [Op.in]: [2]
          },
          paperId,
          userId: ctx.user.id
        },
        transaction: t
      })
      const examHistory = await ExamHistory.create(createObj, {
        transaction: t
      })
    } else if (finaType === 3) {
      // 收藏作答
      await ExamHistory.destroy({
        where: {
          type: {
            [Op.in]: [3]
          },
          paperId,
          userId: ctx.user.id
        },
        transaction: t
      })
      const examHistory = await ExamHistory.create(createObj, {
        transaction: t
      })
    }
    await t.commit()
    ctx.body = R.success()
  } catch (error) {
    console.log(error, 'examHist')
    await t.rollback()
    ctx.body = R.error(ERROR_USER_CODE.EXAM_HISTORY_CREATE_ERROR)
  }
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 批量删除考试记录接口
 * @param {*} ctx
 */
module.exports.delExamHistorys = async (ctx) => {
  await delModel(
    ExamHistory,
    ERROR_USER_CODE.EXAM_HISTORY_DEL_ERROR,
    'examHistoryIds'
  )(ctx)
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 考试记录排序接口
 * @param {*} ctx
 */
module.exports.sortExamHistorys = async (ctx) => {
  // 传递的考试记录ID顺序即为排序顺序，取出这些ID对应的sort，sort从小到大排序后，依次赋值
  await sortModel(
    ExamHistory,
    ERROR_USER_CODE.EXAM_HISTORY_SORT_ERROR,
    'examHistoryIds'
  )(ctx)
}
